<template>
  <div>
    <el-form :inline="true">
      <el-form-item label="一级分类">
        <el-select v-model="form.selectionOne" :disabled="selectDisabled" @focus="getCategoryOneData" @change="handleClearOne" placeholder="请选择" filterable>
          <el-option v-for="(item) in categoryOne" :key="item.id" :label="item.name" :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="二级分类">
        <el-select v-model="form.selectionTwo" :disabled="selectDisabled" @focus="getCategoryTwoData(form.selectionOne)" @change="handleClearTwo" placeholder="请选择" filterable>
          <el-option v-for="(item) in categoryTwo" :key="item.id" :label="item.name" :value="item.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="三级分类">
        <el-select v-model="form.selectionThree" :disabled="selectDisabled" @focus="getCategoryThreeData(form.selectionTwo)" @change="handleSelectThree" placeholder="请选择" filterable>
          <el-option v-for="(item) in categoryThree" :key="item.id" :label="item.name" :value="item.id"/>
        </el-select>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getCategoryOne, getCategoryTwo, getCategoryThree } from '@/api/product/attr'
export default {
  name: 'CategorySelect',
  props:{
    selectDisabled:{
      type:Boolean,
      default:false
    }
  },
  data() {
    return {
      categoryOne: [],
      categoryTwo: [],
      categoryThree: [],
      form:{
        selectionOne:'',
        selectionTwo:'',
        selectionThree:''
      }
    }
  },
  methods: {
    // 获取一级分类数据
    async getCategoryOneData() {
      if (this.categoryOne.length===0) {
        const res = await getCategoryOne()
        // console.log(res)
        this.categoryOne = res
      }
    },
    // 获取二级分类数据
    async getCategoryTwoData(id){
      if (this.form.selectionOne !== '' && this.form.selectionTwo === '') {
        const res = await getCategoryTwo(id)
        this.categoryTwo = res
      }
    },
    // 获取三级分类数据
    async getCategoryThreeData(id){
      if (this.form.selectionTwo !== '' && this.form.selectionThree === '') {
        const res = await getCategoryThree(id)
        // console.log(res)
        this.categoryThree = res
      }
    },
    // 一级分类改变时触发事件
    handleClearOne(){
      this.form.selectionTwo = ''
      this.form.selectionThree = ''
      this.categoryTwo=[]
      this.categoryThree=[]
      this.$emit('watchBtnShow',true)
    },
    // 二级分类改变时触发事件
    handleClearTwo(){
      this.form.selectionThree = ''
      this.categoryThree=[]
      this.$emit('watchBtnShow',true)
    },
    // 三级分类改变时触发事件
    handleSelectThree(){
      this.$emit('getData', this.form)
      this.$emit('watchBtnShow',false)
    }
  }
}
</script>

<style></style>
